<template>
  <div class="page-content sc">
    <div class="page-title">公告管理</div>
    <div class="content-box">
      <a-button
        type="primary"
        style="margin-bottom: 30px;margin-left: 40px;"
        @click="toEdit('', 0)"
      >
        新增公告
      </a-button>
      <div class="search">
        <div class="search-line big-name clearfix">
          <div class="fl clearfix input-box">
            <span class="name fl">状态：</span>
            <a-select
              default-value="请选择"
              :value="searchParams.isPublish"
              @change="selectPublish"
            >
              <a-select-option value=""> 请选择 </a-select-option>
              <a-select-option :value="0"> 未发布 </a-select-option>
              <a-select-option :value="1"> 已发布 </a-select-option>
            </a-select>
          </div>
        </div>
      </div>
      <div class="tabel">
        <a-table
          :columns="columns"
          :data-source="data"
          rowKey="id"
          :pagination="pagination"
          @change="handleTableChange"
        >
          <span slot="isPublish" slot-scope="text, record">
            <span class="state no-auth" v-if="!record.isPublish">未发布</span>
            <span class="state ing-auth" v-else>已发布</span>
          </span>
          <span slot="handler" slot-scope="record">
            <a
              class="handler-item"
              v-if="record.isPublish"
              href="javascript:void(0);"
              @click="toDetail(record, 1)"
              >详情</a
            >
            <a
              class="handler-item"
              v-if="!record.isPublish"
              href="javascript:void(0);"
              @click="toEdit(record, 2)"
              >编辑</a
            >
            <a
              class="handler-item"
              v-if="!record.isPublish"
              href="javascript:void(0);"
              @click="toPublish(record.id)"
              >发布</a
            >
            <a
              class="handler-item"
              v-if="!record.isPublish"
              href="javascript:void(0);"
              @click="deleteJob(record.id)"
              >删除</a
            >
            <a
              class="handler-item"
              v-if="record.isPublish"
              href="javascript:void(0);"
              @click="cancelPublish(record.id)"
              >取消发布</a
            >
          </span>
        </a-table>
      </div>
    </div>
    <a-modal v-model="visibleModel" destroyOnClose :width="800" :title="modelTitle" @ok="editOk">
      <div class="info">
        <div class="info-detail">
          <div class="info-item clearfix">
            <div class="front fl" style="width: 120px;">
              <span class="dot">*</span>
              <span>公告标题: </span>
            </div>
            <div class="word fl" style="width: 550px;">
              <input
                type="text"
                placeholder="请输入"
                :disabled="isEditOrDetail === 1"
                v-model="editRecord.title"
              />
            </div>
          </div>
          <div class="info-item clearfix">
            <div class="front fl" style="width: 120px;">
              <span class="dot">*</span>
              <span>公告内容: </span>
            </div>
            <div class="word fl" style="width: 550px;">
              <textarea
                v-if="isEditOrDetail !== 1"
                type="text"
                v-model="editRecord.detail"
                style="height: 360px; padding:5px 10px;"
                placeholder="请输入"
              />
              <div v-else>{{ editRecord.detail }}</div>
            </div>
          </div>
          <div class="info-item clearfix">
            <div class="front fl" style="width: 120px;">
              <!-- <span class="dot">*</span> -->
              <span>上传图片: </span>
            </div>
            <div class="word fl" style="width: 550px;">
              <a-upload
                v-if="isEditOrDetail !== 1"
                name="file"
                list-type="picture-card"
                class="avatar-uploader"
                :show-upload-list="true"
                :default-file-list="defaultUrlList"
                :action="actionUrl"
                :before-upload="beforeUpload"
                @change="handleChange"
              >
                <div>
                  <a-icon style="font-size: 30px;" :type="loading ? 'loading' : 'plus'" />
                  <div class="ant-upload-text" style="font-size: 16px;">
                    上传
                  </div>
                  <!-- <p>图片建议尺寸375px*176px，大小不超过5M</p> -->
                </div>
              </a-upload>
              <div v-else class="clearfix">
                <img class="fl" v-for="item in editRecord.urlList" :key="item" :src="item" alt="" width="200px" />
              </div>
            </div>
          </div>
          <div class="info-item clearfix" v-if="isEditOrDetail !== 1">
            <div class="front fl" style="width: 120px;">
              <span class="dot">*</span>
              <span>发布设置: </span>
            </div>
            <div class="word fl">
              <a-radio-group
                :defaultValue="editIspublish"
                :options="isPublishOptions"
                @change="radioChange"
              />
            </div>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
const columns = [
  {
    title: '序号',
    dataIndex: 'no',
    key: 'no',
    align: 'center'
  },
  {
    title: '公告标题',
    dataIndex: 'title',
    align: 'center'
  },
  {
    title: '公告内容',
    dataIndex: 'detail',
    align: 'center'
  },
  {
    title: '更新时间',
    dataIndex: 'updateTimeStr',
    align: 'center'
  },
  {
    title: '状态',
    // dataIndex: "isPublish",
    scopedSlots: { customRender: 'isPublish' },
    align: 'center'
  },
  {
    title: '操作',
    // key: "handler",
    align: 'center',
    scopedSlots: { customRender: 'handler' }
  }
]

export default {
  data() {
    return {
      loading: false,
      actionUrl: process.env.VUE_APP_API_BASE_URL + '/images',
      data: [],
      columns,
      visibleModel: false,
      modelTitle: '',
      isEditOrDetail: 1, // 1-详情，2-编辑, 0-新增
      editIspublish: 1,
      isPublishOptions: [
        { label: '立即发布', value: 1 },
        { label: '暂不发布', value: 0 }
      ],
      pagination: {
        showQuickJumper: true,
        current: 1,
        pageSize: this.$config.pageSize,
        total: 1,
        showTotal: (total, range) =>
          `共 ${total} 条记录 第${Math.ceil(range[0] / this.pagination.pageSize)} / ${Math.ceil(
            total / this.pagination.pageSize
          )} 页`
      },
      searchParams: {
        isPublish: '',
        pageNo: 1,
        pageSize: this.$config.pageSize
      },
      urlList:[],
      defaultUrlList: [],
      editRecord: {}
    }
  },
  mounted() {
    this.init()
  },
  watch: {
    '$route.path': function(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.init()
      }
    }
  },
  methods: {
    init() {
      this.searchParams.isPublish = ''
      this.searchParams.pageNo = 1
      this.searchParams.pageSize = this.$config.pageSize
      this.getList()
    },
    getList() {
      this.$http
        .get('/notification/notifications', {
          params: this.searchParams
        })
        .then((res) => {
          if (res.success) {
            this.pagination.current = res.model.pageNo
            this.pagination.total = res.model.totalCount
            this.data = res.model.data.map((item, index) => {
              item.no = index + 1
              return item
            })
          } else {
            this.$message.error(res.message)
          }
        })
    },
    handleTableChange(pagination) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.searchParams.pageNo = pagination.current
      this.getList()
    },
    selectPublish(value) {
      this.searchParams.pageNo = 1
      this.searchParams.isPublish = value
      this.getList()
    },
    // 发布
    toPublish(id) {
      this.$http
        .put('/notification/notification-statuses/' + id, { isPublish: 1 })
        .then((res) => {
          if (res.success) {
            this.getList()
            this.$message.success('发布成功！')
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(() => {
          this.$message.error('发布失败')
        })
    },
    // 取消发布
    cancelPublish(id) {
      this.$http
        .put('/notification/notification-statuses/' + id, { isPublish: 0 })
        .then((res) => {
          if (res.success) {
            this.getList()
            this.$message.success('取消发布成功！')
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(() => {
          this.$message.error('取消发布失败')
        })
    },
    // 删除
    deleteJob(id) {
      this.$confirm({
        title: '提示',
        content: '确认删除此岗位',
        onOk: () => {
          this.$http
            .delete('/notification/notifications/' + id)
            .then((res) => {
              if (res.success) {
                this.getList()
                this.$message.success('删除成功')
              } else {
                this.$message.error('删除失败')
              }
            })
            .catch(() => {
              this.$message.error('删除失败')
            })
        }
      })
    },
    // 详情
    toDetail(record, type) {
      this.modelTitle = '公告详情'
      this.isEditOrDetail = type
      this.editRecord.id = record.id
      this.editRecord.title = record.title
      this.editRecord.detail = record.detail
      this.editRecord.urlList = record.urlList
      this.visibleModel = true
    },
    // 编辑
    toEdit(record, type) {
      this.modelTitle = record ? '编辑公告' : '新增公告'
      this.isEditOrDetail = type
      this.defaultUrlList = []
      if(record) {
        this.editRecord.id = record.id
        this.editIspublish = record.isPublish
        this.urlList = record.urlList
        if(this.urlList && this.urlList.length > 0) {
          this.urlList.map((item, index) => {
            this.defaultUrlList.push({
              uid: index,
              status: 'done',
              url: item
            })
          })
        }
      } else {
        this.editIspublish = 1
      }
      this.editRecord.title = record ? record.title : ''
      this.editRecord.detail = record ? record.detail : ''
      // this.editRecord.urlList = record ? record.urlList : []
      this.visibleModel = true
    },
    editOk() {
      if (this.isEditOrDetail === 1) {
        this.visibleModel = false
      }
      if (this.isEditOrDetail === 2) {
        let params = Object.assign(this.editRecord, { isPublish: this.editIspublish, urlList: this.urlList })
        this.$http.put('/notification', params).then((res) => {
          if (res.success) {
            this.visibleModel = false
            this.getList()
            this.$message.success('保存成功')
          } else {
            this.$message.error(res.message)
          }
        })
      }
      if (this.isEditOrDetail === 0) {
        let params = Object.assign(this.editRecord, { isPublish: this.editIspublish, urlList: this.urlList})
        this.$http.post('/notification', params).then((res) => {
          if (res.success) {
            this.visibleModel = false
            this.getList()
            this.$message.success('新增成功')
          } else {
            this.$message.error(res.message)
          }
        })
      }
    },
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.loading = true
      }
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          const image = info.file.response.model
          this.urlList.push(image)
          this.loading = false
        } else {
          this.$message.error(info.file.response.message)
        }
      }
      if (info.file.status === 'removed') {
        this.urlList = this.urlList.filter(item => {
          return item !== info.file.url
        })
      }
      this.loading = false
    },
     beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('图片格式错误!')
      }
      const isLt2M = file.size / 1024 / 1024 < 5
      if (!isLt2M) {
        this.$message.error('图片大小不能超过5M!')
      }
      return isJpgOrPng && isLt2M
    },
    radioChange(res) {
      this.editRecordStatus = res.target.value
      this.editIspublish = res.target.value
    },
  }
}
</script>

<style lang="less">
.sc .ant-table td {
  white-space: nowrap;
  max-width: 300px;
}
</style>
